﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Serialization;
using System.Reflection;



namespace WcfServices.ServiceInterfaces
{
    public class IgnorableSerializerContractResolver : DefaultContractResolver
    {
        private readonly ISet<string> PropertieIgnore;
        private readonly ISet<Type> TypeIgnore;

        public IgnorableSerializerContractResolver()
        {
            TypeIgnore = new HashSet<Type>();
            PropertieIgnore = new HashSet<string>();
        }

       
        public void Ignore(Type type)
        {
            TypeIgnore.Add(type);
        }

        public void Ignore(string propertie){
            
            PropertieIgnore.Add(propertie);
        }

    
        private bool IsIgnored(Type type, string propertyName)
        {
            
            return PropertieIgnore.Contains(propertyName) 
                || TypeIgnore.Contains(type) 
                || (type.IsGenericType && TypeIgnore.Contains(type.GetGenericTypeDefinition())) ;
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            
            JsonProperty property = base.CreateProperty(member, memberSerialization);
            
            if (this.IsIgnored(property.DeclaringType, property.PropertyName)
            || (this.IsIgnored(property.DeclaringType.BaseType, property.PropertyName))
            ||(this.IsIgnored(property.PropertyType, property.PropertyName)))
            {
                property.ShouldSerialize = instance => { return false; };
            }

            return property;
        }
    }
}